package com.huixiong.countDownLatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <描述>
 *
 * @author timothy.yang cloudwise
 * @since 2022-05-22 11:58
 */
public class CountDownLatchMain {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            Runnable runnable = () -> {
                try {
                    System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
                    Thread.sleep((long) Math.random() * 100000);
                    System.out.println("子线程" + Thread.currentThread().getName() + "执行完成");
                    countDownLatch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };

            executorService.execute(runnable);
        }

        try {
            System.out.println("主线程" + Thread.currentThread().getName() + "等待子线程执行完成...");
            countDownLatch.await(30, TimeUnit.SECONDS);// 阻塞当前线程,知道计数器的值为0
            System.out.println("主线程" + Thread.currentThread().getName() + " 开始执行...");
            executorService.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}